<template>
  <div class="container">
    <!-- 头部数据统计 -->
    <el-row
      :gutter="10"
      class="header-data"
      type="flex"
    >
      <el-col
        :span="12"
        class="total"
      >
        <div>
          <div class="fontA">总访客数</div>
          <div class="fontB">{{headerData.statTotalUserCount}}</div>
        </div>

      </el-col>
      <div class="line-A"></div>
      <el-col
        :span="6"
        class=" flex flex-col flex-one"
      >

        <div class="fontA">今日活跃用户</div>
        <div class="fontB">{{headerData.statTodayUserCount}}</div>
      </el-col>
      <div class="line-A"></div>
      <el-col
        :span="6"
        class="flex flex-col flex-one"
      >
        <div class="fontA">7日活跃用户</div>
        <div class="fontB">{{headerData.statSevenDayUserCount}}</div>
      </el-col>
    </el-row>
    <!-- 筛选 -->
    <el-row
      :gutter="10"
      class="select "
    >
      <el-col
        :span="12"
        class="left-wrap"
      >
        <div class="block">
          <span
            :class="curIndex===0  ? 'demonstration-active' : 'demonstration'"
            @click="getList(1)"
          >今日</span>
          <span
            :class="curIndex===1  ? 'demonstration-active' : 'demonstration'"
            @click="getList(2)"
          >昨日</span>
          <span
            :class="curIndex===2  ? 'demonstration-active' : 'demonstration'"
            @click="getList(3)"
          >7日</span>
          <span
            :class="curIndex===3  ? 'demonstration-active' : 'demonstration'"
            @click="getList(4)"
          >30日</span>
          <el-date-picker
            v-model="timeData"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            @change="chooseDate"
            end-placeholder="结束日期"
          >
          </el-date-picker>
          <el-button
            type="primary"
            style="margin-left:16px;background:#015DFF"
            @click="selectDate"
            :loading="loading"
          >查询</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="flex  flex-one flex-center">
          <div class="flex-one">
            <div class="fontA">访客数</div>
            <div class="fontD">{{headerData.statUserCount}}</div>
          </div>
          <div class="line"></div>
          <div class="flex-one">
            <div class="fontA">访问次数</div>
            <div class="fontD">{{headerData.statAccessCount}}</div>
          </div>
          <div class="line"></div>
          <div class="flex-one">
            <div class="fontA">新增访客</div>
            <div class="fontD">{{headerData.statAdditionUserCount}}</div>
          </div>
          <div class="line"></div>
          <div class="flex-one">
            <div class="fontA">新增访客占比</div>
            <div class="fontD">{{headerData.statAdditionUserRate}}</div>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 图表 -->
    <el-row
      :gutter="10"
      style="margin-bottom:20px"
    >

      <el-col :span="12">
        <el-card>
          <div slot="header">访问数量</div>
          <div
            id="chart1"
            style="width:100%;height: 500px"
            
          ></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">访客来源</div>
          <div style="position: relative;">
            <div
              id="chart2"
              style="width:100%;height: 500px;position: relative;"
            >

            </div>
            <!-- 切换 -->
            <div class="tab-wrap flex flex-center">
              <div
                :class="sourceIndex == 0 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(0,1)"
              >访客</div>
              <div
                :class="sourceIndex == 1 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(1,1)"
              >新增</div>
            </div>
          </div>

        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col
        :span="12"
        style="margin-bottom:20px"
      >
        <el-card>
          <div slot="header">性别统计</div>
          <div style="position: relative;">
            <div
              id="chart3"
              style="width:600px;height: 500px"
            >
            </div>
            <!-- 切换 -->
            <div class="tab-wrap flex flex-center">
              <div
                :class="sexIndex == 0 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(0,2)"
              >访客</div>
              <div
                :class="sexIndex == 1 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(1,2)"
              >新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">年龄统计</div>
          <div style=";position: relative;">
            <div
              id="chart4"
              style="width:100%;height: 500px"
            ></div>
            <!-- 切换 -->
            <div class="tab-wrap flex flex-center">
              <div
                :class="ageIndex == 0 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(0,3)"
              >访客</div>
              <div
                :class="ageIndex == 1 ?  'act-tab-wrap-item' : 'tab-wrap-item'"
                @click="changeNav(1,3)"
              >新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 数据看板 -->
    <el-row :gutter="10">
      <el-card>
        <div slot="header">数据看板</div>
        <el-col :span="5">
          <div class="list-wrap">
            <div class="map-title">地域访问次数</div>
            <div class="option-wrap flex flex-center">
              <div class="option font">
                序号
              </div>
              <div class="option font">
                地区
              </div>
              <div class="option font">
                次数
              </div>
              <div class="option font">
                占比
              </div>
            </div>
            <div
              class="flex flex-center flex-one item-data"
              v-for="(item,index) of dataList"
              :key="index"
            >
              <div
                class="font "
                :class="index <=2 ? 'option-index-top3' : 'option-index'"
              >{{index + 1}}</div>
              <div class="font option-region">{{item.name}}</div>
              <div class="font option-times">{{item.value}}</div>
              <div class="font option-proportion">{{item.proportion}}%</div>
            </div>
          </div>

        </el-col>
        <el-col :span="19">
          <div slot="header">数据看板</div>
          <div
            id="chart5"
            style="float:left;width:100%;height: 670px"
          ></div>

        </el-col>
      </el-card>

    </el-row>
  </div>
</template>

<script>
// import x from ''
import * as echarts from 'echarts'
// 引入地图
import 'echarts/lib/chart/map'
// 引入js
import '@/vendor/map/js/china.js'

import utils from '@/utils/index'
import {
  getHeaderData,
  getTimeDimVisitorUser,
  getVisitorSource,
  getVisitorSex,
  getVisitorAge,
  getMapData
  
} from '@/api/visitor'
import { setTimeout } from 'timers';

export default {
  components: {},
  data() {
    return {
      timeData: [],
      list: [{}, {}, {}, {}, {}, {}, {}, {}, {}],
      dataList: [],
      dateList: {},
      curIndex: 0,
      sourceIndex: 0, // 访客tab切换
      sourceList: [], // 访客列表
      sexIndex: 0, // 性别tab切换
      sexList: [], // 性别列表
      ageIndex: 0, // 年龄tab切换
      ageList: [], // 年龄tab切换
      headerData: {},
      loading: false,
    }
  },
  computed: {},
  watch: {},
  mounted() {
    this.defaultDate()
    this.selectDate()
  },
  methods: {
    // 查询图表信息
    selectDate(){
      if(this.loading) return
      // this.dataList.beginDate = this.timeData[0]
      // this.dataList.endDate = this.timeData[1]
      // return
      this.loading = true
      this.getHeaderDatas().then(res=>{
        this.initChart1().then(res => {
          this.initChart2().then(res => {
            this.initChart3().then(res=> {
              this.initChart4().then(res => {
                this.initMap().then(res => {
                  this.loading = false
                }).catch(() => {
                  console.log('图表加载失败')
                  this.loading = false
                })  
              }).catch(() => {
                console.log('图表加载失败')
                this.loading = false
              })  
            }).catch(() => {
              console.log('图表加载失败')
              this.loading = false
            })  
          }).catch(() => {
            console.log('图表加载失败')
            this.loading = false
          })  
        }).catch(() => {
          console.log('图表加载失败')
          this.loading = false
        })  
      }).catch(() => {
        console.log('图表加载失败')
        this.loading = false
      })
    },
    // 获取头部数据
    getHeaderDatas() {
      return new Promise((resolve, reject) => {
        getHeaderData(this.dateList).then(res => {
          this.headerData = res.data
          resolve(1)
        }).catch(res => {
          reject(0)
        })
      })
    },
    changeNav(index, type) {
      //index: 0.访客  1.新增
      if(this.loading) return
      //type: 1. 访客来源  2.性别统计   3.年龄统计
      switch (type) {
        case 1:
          this.sourceIndex = index
          this.initChart2()
          break
        case 2:
          this.sexIndex = index
          this.initChart3()
          break
        case 3:
          this.ageIndex = index
          this.initChart4()
          break

        default:
          break
      }
    },
    // 批量渲染
    request() {},
    // 默认时间
    defaultDate() {
      let startTime = new Date(new Date().toLocaleDateString()).getTime(),
        endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1
      this.dateList = {
        beginDate: utils.formatDate(startTime, 'yyyy-MM-dd hh:mm:ss', true),
        endDate: utils.formatDate(endTime, 'yyyy-MM-dd hh:mm:ss', true),
      }
      this.timeData.push(utils.formatDate(startTime, 'yyyy-MM-dd hh:mm:ss', true))
      this.timeData.push(utils.formatDate(endTime, 'yyyy-MM-dd hh:mm:ss', true))
    },
    // 时间选择
    chooseDate(e) {
      let start = new Date(e[0]).getTime(),
        end = new Date(e[1]).getTime()
        
      this.dateList = {
        beginDate: utils.formatDate(start, 'yyyy-MM-dd hh:mm:ss', true),
        endDate: utils.formatDate(end, 'yyyy-MM-dd hh:mm:ss', true),
      }
    },
    // 筛选
    getList(type) {
      // 1 今日    2.昨日    3.7日  4.30日
      let startTime = new Date(new Date().toLocaleDateString()).getTime(),
         endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1
      let date = {
        // 今天
        today: {
          startTime: startTime,
          endTime: endTime
        },
        // 昨天
        yestoday: {
          startTime: startTime - 24 * 60 * 60 * 1000,
          endTime: endTime - 24 * 60 * 60 * 1000
        },
        // 7天前
        after7day: {
          startTime: startTime - 24 * 60 * 60 * 7 * 1000,
          endTime:   endTime - 24 * 60 * 60 * 7 * 1000
        },
        // 30天前
        after30day: {
          startTime: startTime - 24 * 60 * 60 * 30 * 1000,
          endTime:   endTime - 24 * 60 * 60 * 30 * 1000
        }
      }

      switch (type) {
        case 1:
          this.curIndex = 0
          this.timeData = []
          this.timeData.push(
            utils.formatDate(date.today.startTime, 'yyyy-MM-dd hh:mm:ss', true)
          )
          this.timeData.push(
            utils.formatDate(date.today.endTime, 'yyyy-MM-dd hh:mm:ss', true)
          )
          this.dateList = {
            beginDate: utils.formatDate(date.today.startTime, 'yyyy-MM-dd hh:mm:ss',true),
            endDate: utils.formatDate(date.today.endTime, 'yyyy-MM-dd hh:mm:ss',true),
            type: '1'
          }
          // this.selectDate()
          break
        case 2:
          this.curIndex = 1
          this.timeData = []

          this.timeData.push(utils.formatDate(date.yestoday.startTime, 'yyyy-MM-dd hh:mm:ss', true))
          this.timeData.push(utils.formatDate(date.yestoday.endTime, 'yyyy-MM-dd hh:mm:ss', true))
          this.dateList = {
            beginDate: utils.formatDate(date.yestoday.startTime,'yyyy-MM-dd hh:mm:ss',true),
            endDate: utils.formatDate(date.yestoday.endTime,'yyyy-MM-dd hh:mm:ss',true),
            type: '1'
          }
          
          break
        case 3:
          this.curIndex = 2
          this.timeData = []
          this.timeData.push(utils.formatDate(date.after7day.startTime,'yyyy-MM-dd hh:mm:ss',true))
          this.timeData.push(utils.formatDate(date.today.endTime, 'yyyy-MM-dd hh:mm:ss', true))
          this.dateList = {
            beginDate: utils.formatDate(date.after7day.startTime,'yyyy-MM-dd hh:mm:ss',true),
            endDate: utils.formatDate(date.today.endTime,'yyyy-MM-dd hh:mm:ss',true),
          }
          
          break
        case 4:
          this.curIndex = 3
          this.timeData = []
          this.timeData.push(utils.formatDate(date.after30day.startTime,'yyyy-MM-dd hh:mm:ss',true))
          this.timeData.push(utils.formatDate(date.today.endTime, 'yyyy-MM-dd hh:mm:ss', true))
          this.dateList = {
            beginDate: utils.formatDate(date.after30day.startTime,'yyyy-MM-dd hh:mm:ss',true),
            endDate: utils.formatDate(date.today.endTime,'yyyy-MM-dd hh:mm:ss',true),
          }
          
        //  this.selectDate()
          break
        default:
          break
      }
    },

    initChart1() {
      return new Promise((resolve, reject) => {
        let start = new Date(this.dateList.beginDate).getTime()
        let end = new Date(this.dateList.endDate).getTime()
        this.dateList.type = start - end > 60*60*24*1000 ? '0' : '1'
        getTimeDimVisitorUser(this.dateList).then(res => {
          resolve(1)
          
          let timeList = []
          this.sourceList = res.data
          this.sourceList[0].map(item => {
            let time = new Date(item).getTime()
            if(this.dateList.type == 1){
              timeList.push(utils.formatDate(time, 'hh:mm', true))
            } else {
              timeList.push(utils.formatDate(time, 'MM-dd', true))
            }
          })
          var myChart = echarts.init(document.getElementById('chart1'))
          let option = {
            legend: {
              data: ['苹果', '香蕉'],
              left: 'right'
            },

            xAxis: {
              type: 'category',
              data: timeList
            },
            yAxis: {
              type: 'value'
            },
            series: this.sourceList[1],
            tooltip: {
              trigger: 'axis'
            }
          }
          myChart.setOption(option)
          delete this.dateList.type
        }).catch(() => {
          reject(0)
        })
      })
    },
    initChart2() {
      return new Promise((resolve, reject) => {
        getVisitorSource(this.dateList).then(res => {
          resolve(1)
          
          if (this.sourceIndex == 0) {
            this.sourceList = res.data[0]
          } else {
            this.sourceList = res.data[1]
          }
          var myChart = echarts.init(document.getElementById('chart2'))
          var _that = this
          let option = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right',
              formatter: function(name) {
                var total = 0
                var tarValue
                for (var i = 0; i < _that.sourceList.length; i++) {
                  total += _that.sourceList[i].value
                  if (name == _that.sourceList[i].name) {
                    tarValue = _that.sourceList[i].value
                  }
                }
                var p = ((tarValue / total) * 100).toFixed(2)
                return name + '|' + p + '%'
              }
            },
            series: [
              {
                name: '访问来源',
                type: 'pie',
                radius: '50%',
                data: this.sourceList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          myChart.setOption(option)
        }).catch(() => {
          reject(0)
        })
      })
    },
    initChart3() {
      return new Promise((resolve, reject) => {
        getVisitorSex(this.dateList).then(res => {
          resolve(1)
          
          if (this.sexIndex == 0) {
            this.sexList = res.data[0]
          } else {
            this.sexList = res.data[1]
          }
          var myChart = echarts.init(document.getElementById('chart3'))
          var _that = this
          let option = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right',
              formatter: function(name) {
                var total = 0
                var tarValue
                for (var i = 0; i < _that.sexList.length; i++) {
                  total += _that.sexList[i].value
                  if (name == _that.sexList[i].name) {
                    tarValue = _that.sexList[i].value
                  }
                }
                var p = ((tarValue / total) * 100).toFixed(2)
                return name + '|' + p + '%'
              }
            },
            series: [
              {
                name: '访问来源',
                type: 'pie',
                radius: ['30%', '40%'],
                data: this.sexList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          myChart.setOption(option)
        }).then(() => {
          reject(0)
        })
      })
    },
    initChart4() {
      return new Promise((resolve, reject) => {
        getVisitorAge(this.dateList).then(res => {
          resolve(1)
          
          if (this.sexIndex == 0) {
            this.ageList = res.data[0]
          } else {
            this.ageList = res.data[1]
          }
          var myChart = echarts.init(document.getElementById('chart4'))
          var _that = this
          let option = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'right',
              formatter: function(name) {
                var total = 0
                var tarValue
                for (var i = 0; i < _that.ageList.length; i++) {
                  total += _that.ageList[i].value
                  if (name == _that.ageList[i].name) {
                    tarValue = _that.ageList[i].value
                  }
                }
                var p = ((tarValue / total) * 100).toFixed(2)
                return name + '|' + p + '%'
              }
            },
            series: [
              {
                name: '访问来源',
                type: 'pie',
                radius: ['30%', '40%'],
                data: this.ageList,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          myChart.setOption(option)
        }).catch(() => {
          reject(0)
        })
      })
    },
    initMap() {
      return new Promise((resolve, reject) => {
        getMapData(this.dateList).then(res => {
          resolve(1)
          
          var myChart = echarts.init(document.getElementById('chart5'))
          this.dataList = res.data
          var total = 0;
          var tarValue;
          this.dataList.map(item => {
            total += item.value
          })
          this.dataList.map(item => {
            item.proportion = (item.value / total * 100).toFixed(2)
          })

          let option = {
            backgroundColor: '#1d293a',
            tooltip: {
              formatter: function(params, ticket, callback) {
                return (
                  params.seriesName + '<br />' + params.name + '：' + params.value
                )
              }
            },
            visualMap: {
              min: 0,
              max: 1500,
              left: 'left',
              top: 'bottom',
              text: ['高', '低'],
              inRange: {
                color: ['#e0ffff', '#006edd']
              },
              show: true
            },
            geo: {
              map: 'china',
              roam: false,
              zoom: 1.23,
              label: {
                normal: {
                  show: true,
                  fontSize: '10',
                  color: 'rgba(0,0,0,0.7)'
                }
              },
              itemStyle: {
                normal: {
                  borderColor: 'rgba(0, 0, 0, 0.2)'
                },
                emphasis: {
                  areaColor: '#F3B329',
                  shadowOffsetX: 0,
                  shadowOffsetY: 0,
                  shadowBlur: 20,
                  borderWidth: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            },
            series: [
              {
                name: '信息量',
                type: 'map',
                geoIndex: 0,
                data: this.dataList
              }
            ]
          }
          myChart.setOption(option)
          myChart.on('click', function(params) {
            alert(params.name + ':' + params.seriesName + ':' + params.value)
          })
          myChart.resize()
        }).catch(() => {
          reject(0)
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  margin: 20px 28px;
}
.header-data {
  // width: 1600px;
  height: 130px;
  background: #ffffff;
  border-radius: 2px;
  padding-top: 32px;
  box-sizing: border-box;
}
.total {
  text-align: center;
}

.fontB {
  margin-top: 12px;
  font-size: 28px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
}
.fontD {
  font-size: 20px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #444444;
}

.select {
  height: 84px;
  background: #ffffff;
  border-radius: 2px;
  margin: 20px 0;
}
.left-wrap {
  // line-height: 84px;
}
.block {
  margin-top: 22px;
  margin-left: 29px;
}
.option {
  margin-right: 40px;
}

.demonstration {
  margin-right: 24px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.65);
}
.demonstration-active {
  margin-right: 24px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  // color: rgba(0, 0, 0, 0.65);
  color: #015dff;
}
.text-right {
  text-align: right;
}
.map-title {
  margin-top: 43px;
  margin-bottom: 25px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
}
.option-wrap {
  margin-bottom: 22px;
}
.line-A {
  width: 1px;
  height: 78px;
  background: #e9e9e9;
  margin-right: 20px;
}
.line {
  width: 1px;
  height: 50px;
  margin-right: 20px;
  background: #e9e9e9;
  margin-top: 16px;
}

.fontA {
  margin-top: 16px;
  margin-bottom: 4px;
}
.list-wrap {
  width: 363px;
  height: 670px;
  background: #1d293a;
  padding: 11px 34px 11px 53px;
  box-sizing: border-box;
}
.font {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
}
.item-data {
  margin-bottom: 18px;
}
.option-index {
  margin-left: 10px;
  width: 20px;
  height: 20px;
  background: #f0f2f5;
  line-height: 20px;
  text-align: center;
  font-size: 12px;
  font-family: HelveticaNeue-Medium, HelveticaNeue;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
  border-radius: 50%;
}
.option-index-top3 {
  margin-left: 10px;
  width: 20px;
  height: 20px;
  background: #015dff;
  line-height: 20px;
  text-align: center;
  font-size: 12px;
  font-family: HelveticaNeue-Medium, HelveticaNeue;
  font-weight: 500;
  color: #ffffff;
  border-radius: 50%;
}
.option-region {
  width: 60px;
  margin-left: 40px;
}
.option-times {
  width: 30px;
  margin-left: 10px;
}
.option-proportion {
  width: 40px;
  margin-left: 40px;
}
// tab 切换
.tab-wrap {
  position: absolute;
  left: 0;
  top: 5px;
  border-radius: 4px;

  border: 1px solid #acb3bf;
  padding: 0;
  box-sizing: border-box;
  .tab-wrap-item {
    width: 80px;
    height: 36px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #8e959f;
    line-height: 36px;
    text-align: center;
  }
  .act-tab-wrap-item {
    width: 80px;
    height: 36px;

    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    line-height: 36px;
    background: #015dff;
    text-align: center;
  }
}
</style>